package genertor;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.zengdb.crm.domain.User;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class CodeGenerator {
	private static Configuration conf = new Configuration();
	private static Map<String, String> tmpls = new HashMap<>();
	
	static{
		try {
			//设置文件模板目录位置
			conf.setDirectoryForTemplateLoading(new File("templates"));
			//设置模板文件对应的真实文件
			tmpls.put("Mapper.java.tmpl","src/main/java/{0}/mapper/{1}Mapper.java");
			tmpls.put("Mapper.xml.tmpl","src/main/resources/{0}/mapper/{1}Mapper.xml");
			tmpls.put("IService.java.tmpl","src/main/java/{0}/service/I{1}Service.java");
			tmpls.put("ServiceImpl.java.tmpl","src/main/java/{0}/service/impl/{1}ServiceImpl.java");
			tmpls.put("QueryObject.java.tmpl","src/main/java/{0}/query/{1}QueryObject.java");
			tmpls.put("Controller.java.tmpl","src/main/java/{0}/web/controller/{1}Controller.java");
			tmpls.put("target.js.tmpl","src/main/webapp/static/js/views/{2}.js");
			tmpls.put("target.jsp.tmpl","src/main/webapp/WEB-INF/views/{2}.jsp");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception{
		codeGenerator(User.class);
		System.out.println("创建文件成功。。。");
		
//		deleteGeneratorFiles(User.class);
//		System.out.println("删除文件成功。。。");
		
	}
	
	@SuppressWarnings("all")
	private static void codeGenerator(Class<?> clazz) throws Exception {
		//数据模型
		ClassInfo classInfo = new ClassInfo(clazz);
		for (Entry<String, String> entry : tmpls.entrySet()) {
			createFile(entry.getKey(), entry.getValue(), classInfo);
		}
	}
	
	/**
	 * 
	 * @param templateName  模板文件名称
	 * @param outPath       文件输出路径
	 * @param classInfo     数据模型
	 */
	private static void createFile(String templateName,String outPath,ClassInfo classInfo) throws Exception{
		Template temp = conf.getTemplate(templateName);
		outPath = MessageFormat.format(outPath, classInfo.getPackageName().replace(".", "/"),classInfo.getClassName(),classInfo.getObjectName());
		File targetFile = new File(outPath);
		//创建目录
		if(!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		temp.process(classInfo, new FileWriter(targetFile));
	}
	
	/**
	 * 删除自动生成的文件
	 * @param clazz 生成的文件对应类的类型
	 * @throws Exception 
	 */
	@SuppressWarnings("all")
	private static void deleteGeneratorFiles(Class<?> clazz) throws Exception{
		ClassInfo classInfo = new ClassInfo(clazz);
		//tmpls.put("", "src/main/java/{0}/domain/{1}.java");
		for (String str : tmpls.values()) {
			String filePath = MessageFormat.format(str, classInfo.getPackageName().replace(".", "/"),classInfo.getClassName(),classInfo.getObjectName());
			File file = new File(filePath);
			if (file.exists()) {
				file.delete();
			}
		}
	}
}
